<?php

class LoginForm extends CFormModel
{
	public $message;
    public $username;
	public $password;
    public $rememberMe; 
    public $admin = false;       

	private $_identity;
    
	public function rules()
	{
		return array(			
			array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('message','safe'),				
		);
	}
    
	public function attributeLabels()
	{
		return array(            
            'username'=>Yii::t('default', 'Username'),
            'password'=>Yii::t('default', 'Password'),
            'rememberMe'=>Yii::t('default','Remember me next time'),
		);
	}
    
	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
        if ($this->_identity === null) {
			$this->_identity = new LetIdentity($this->username, $this->password, $this->admin);            
            $this->_identity->authenticate();
		}
        
		if ($this->_identity->errorCode === LetIdentity::ERROR_NONE) {
			$duration = $this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity, $duration);
            //Member::model()->updateByPk($this->_identity->id, array('lastlogintime'=>time()));
			return true;
		} else {
            $this->addError('message',$this->_identity->messages['error'][0]);            
            return false;
		}
	}
}
